import React from 'react';
import {inject, observer} from 'mobx-react';
import {Spin, Button, Modal, Tooltip, Row, Col} from 'antd';
import {
  WeaReqTop,
  WeaAlertPage,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaNewScroll,
  WeaSearchGroup,
  WeaLocaleProvider
} from 'ecCom';
import SearchGroupBorderLeft from '../SearchGroupBorderLeft';
import DateSelectArea from './DateSelectArea';
import LastMonthWorkSummary from './LastMonthWorkSummary';
import ThisMonthWorkPlan from './ThisMonthWorkPlan';
import PlanLog from './PlanLog';
import Feedback from './Feedback';
import ReportShare from './ReportShare';
import RelatedFiles from './RelatedFiles';
import LeftCom from './LeftCom';
import PlanSummaryModal from './PlanSummaryModal'
import {getParams, getCurrentHeight,setWindowKeys} from '../../../util/Util';
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
const confirm = Modal.confirm;
@inject ('planReportViewStore')
@observer
export default class Index extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      _height: getCurrentHeight (),
      heightInit: false,
      showSearchAd: false,
      topTab: [
        {
          title: getLabel('20617','月报') ,
          viewcondition: '1',
          key: '1',
        },
        {
          title: getLabel('20619','周报') ,
          viewcondition: '2',
          key: '2',
        },
      ],
      tabSelectKey: '1',
      monthWeekSelectComDisplayKey: '',
      currentSelectYear: '',
      currentSelectMonth: '',
      currentSelectWeek: '',
      showLeft: false,
      topButtons: [],
    };
    this.store = this.props.planReportViewStore;
    this.shareRef = React.createRef();
  }

  //周报月报切换事件
  tabChange = v => {
    this.store.locationkey = new Date ().getTime ();
    this.store.tabSelectKey = v;
    this.store.dateSelect.year =''
    this.store.dateSelect.month =''
    this.store.dateSelect.week =''
    this.store.getPlanDetail ();
  };

 //顶部top组件设置
  getWeaReqTopConfig = () => {
    let {planname,resourcename} = this.store.resData
    const title = this.store.tabDatas.length<1?resourcename+getLabel(33851,'计划报告'):this.store.getPlanName(resourcename)
    return {
      // title: getLabel('6015','我的报告'),
      title: planname?planname:title,
      icon: <i className="icon-coms-implement" />,
      iconBgcolor: 'rgb(150, 53, 138)',
      loading: this.store.loading,
      buttons: this.getMenus ().topButtons,
      showDropIcon:true,
      dropMenuDatas:this.getMenus ().rightMune,
      //onDropMenuClick:this.onDropMenuClick,
      tabDatas: this.store.tabDatas,
      selectedKey: this.store.tabSelectKey,
      onChange: this.tabChange,
    };
  };



  //操作事件
  doOperation = operation => {
    this.setState ({operation});
    let content = operation == 'save'
      ? getLabel('509012','未填写标题的明细项将不会保存，确定继续执行操作？') 
      : getLabel('509013','确认提交此报告吗？') ;
    let _this = this;

    if(operation == 'save'){
      if(this.store.uploading){
        this.fileCom.doUpload (operation);
      }else{
        this.store.doOperation (operation);
      }
    }

    if (operation == 'submit') {
      confirm ({
        title: getLabel('508972','确认提示') ,
        content: content,
        onOk () {
          if (
            ( operation == 'submit') && _this.store.uploading
          ) {
            _this.fileCom.doUpload (operation);
          } else {
            _this.store.doOperation (operation);
          }
        },
        onCancel () {},
      });
    }
    
    if(operation!='save' && operation !='submit') {
      this.store.doOperation (operation,this.props.getNoAuditCount);
    }
  };
  //生成右键菜单
  makeRightMenu = (
    key,
    content,
    onClick,
    iconClassName = 'icon-coms-search'
  ) => {
    return {
      key: key,
      icon: <i className={iconClassName} />,
      content: content,
      onClick: onClick,
    };
  };
  //获取菜单（右键和顶部）
  getMenus = () => {
    const planstatus = this.store.resData.planstatus;
    const {authority: {canedit, candel, canaudit, canreset}} = this.store;
    const {buttonAuth: {edit, del, audit, reset, share}} = this.store;
    let rightMune = [];
    let topButtons = [];
    if (reset) {
      rightMune.push (
        this.makeRightMenu (
          '3',
          getLabel('509014','重新编写') ,
          () => {
            this.doOperation ('reset');
          },
          'icon-coms-top'
        )
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@zx7d6p@resetwrite`} title={getLabel('509015','重新编写计划报告') }>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@538yzx@resetwrite`}
            type="primary"
            style={{display: reset ? '' : 'none'}}
            onClick={() => this.doOperation ('reset')}
          >
            {getLabel('509014','重新编写') }
          </Button>
        </Tooltip>
      );
    }
    if (edit) {
      rightMune.push (
        this.makeRightMenu (
          '0',
          getLabel('86','保存'),
          () => {
            this.doOperation ('save');
          },
          'icon-coms-Save-as'
        )
      );
      rightMune.push (
        this.makeRightMenu (
          '1',
          getLabel('615','提交'),
          () => {
            this.doOperation ('submit');
          },
          'icon-coms-top'
        )
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@m9qx8m@save`} title={getLabel('508724','保存为草稿') }>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@368mj2@save`}
            type="primary"
            style={{display: edit ? '' : 'none'}}
            onClick={() => this.doOperation ('save')}
          >
            {getLabel('86','保存')}
          </Button>
        </Tooltip>
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@qwxmot@submit`} title={getLabel('382335','保存并提交')}>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0n6s4l@submit`}
            type="primary"
            style={{display: edit ? '' : 'none'}}
            onClick={() => this.doOperation ('submit')}
          >
            { getLabel('615','提交')}
          </Button>
        </Tooltip>
      );
    }
    if (del) {
      rightMune.push (
        this.makeRightMenu (
          '2',
          getLabel('91','删除') ,
          () => {
            this.doOperation ('del');
          },
          'icon-coms-delete'
        )
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@yn4p04@delete`} title={getLabel('509016','删除此计划报告') }>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@judgoz@delete`}
            type="primary"
            style={{display: del ? '' : 'none'}}
            onClick={() => this.doOperation ('del')}
          >
            {getLabel('91','删除') }
          </Button>
        </Tooltip>
      );
    }

    if (canaudit) {
      rightMune.push (
        this.makeRightMenu (
          '5',
          getLabel('142','批准')  ,
          () => this.doOperation ('approve'),
          'icon-coms-Batch-sharing'
        )
      );
      rightMune.push (
        this.makeRightMenu (
          '6',
          getLabel('236','退回') ,
          () => this.doOperation ('return'),
          'icon-coms-Batch-sharing'
        )
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@g7v3mh@approve`} title={getLabel('509017','批准计划报告')       }>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ku616j@approve`}
            type="primary"
            style={{display: audit ? '' : 'none'}}
            onClick={() => this.doOperation ('approve')}
          >
            {getLabel('142','批准') }
          </Button>
        </Tooltip>
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@qrjg27@return`} title={getLabel('509018','退回计划报告')}>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@elr45n@return`}
            type="primary"
            style={{display: audit ? '' : 'none'}}
            onClick={() => this.doOperation ('return')}
          >
            {getLabel('236','退回') }
          </Button>
        </Tooltip>
      );
    }

    if (share) {
      rightMune.push (
        this.makeRightMenu (
          '4',
          getLabel('119','共享') ,
          () => {
            this.shareRef.current.wrappedInstance.openShareModal ();
          },
          'icon-coms-Batch-sharing'
        )
      );
      topButtons.push (
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@ywrv0v@share`} title={getLabel('509019','共享计划报告') } placement="bottom">
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fuv6og@share`}
          type="primary"
            onClick={() => {
              let refModal = this.shareRef.current.wrappedInstance
              refModal.openShareModal ();
            }}
          >
            {getLabel('119','共享')}
          </Button>
        </Tooltip>
      );
    }

    let menus = {
      topButtons,
      rightMune,
    };

    return menus;
  };
  //关联ref
  refFile = ref => {
    this.fileCom = ref;
  };

  componentWillMount () {
    //一些初始化请求
    //如果是从其他地方跳转过来的
    let params = {};
    //如果url中有planid
    if (getParams ('planid')) {
      params.planid = getParams ('planid');
    } else if (getParams ('resourceid')) {
      this.store.resourceid = getParams ('resourceid');
      this.store.resourcetype = 4;
      params.type1 = getParams ('type1');
      params.type2 = getParams ('type2');
      params.year = getParams ('year');
      params.resourceid = getParams ('resourceid');
      params.resourcetype = 4;
      this.store.onDateChange('year', getParams ('year'),true)
      this.store.tabSelectKey = params.type1;
      if (getParams ('type1') == 1) {
        // this.store.dateSelect.month = parseInt (getParams ('type2'));
        this.store.onDateChange('month', parseInt (getParams ('type2')),true)
      } else {
        // this.store.dateSelect.week = parseInt (getParams ('type2'));
        this.store.onDateChange('week', parseInt (getParams ('type2')),true)
      }
    }
    this.store.locationkey=new Date().getTime()
    this.store.getPlanDetail (params);
    //清空日志请求长度
    this.store.planLog = {
      datas: [],
      lastcount: 0,
      lastid: '',
      status: '',
    };
    //设置windowkey
    setWindowKeys("1",getLabel('6015','我的报告') );
    //刷新审核列表
    if(window.opener  && typeof window.opener.planGetNoAuditCount === 'function'){
      window.opener.planGetNoAuditCount()
    }
    if(typeof this.props.getNoAuditCount == 'function'){
      this.props.getNoAuditCount()
    }
  }

  //点击页面时
  onContextClick = () => {
    this.store.locationkey = new Date ().getTime ();
    this.store.monthWeekSelectComDisplayKey = 'none';
  };
  //点击下属调用方法
  onSubClick(id, name){
    this.store.resourceid = id;
    this.store.resourcename = name;
    this.store.resourcetype = 4;
    this.store.resData.resourceid=id
    this.store.getPlanDetail ();
  };

  render () {
    const { _height} = this.state;
    let {planReportViewStore} = this.props;
    let {
      dateSelect,
      summaryColumns,
      resData,
      noDataMessage,
      msg,
    } = planReportViewStore;
    resData = toJS (resData);
    dateSelect = toJS (dateSelect);
    summaryColumns = toJS (summaryColumns);

    let showMonth = dateSelect.month.length<2?"0"+dateSelect.month:dateSelect.month

    return (
      <div
        className="wea-workrelate-plan-report-view"
        onClick={this.onContextClick}
      >
        {msg != '' &&
           <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@adp3pj`} spinning={this.store.loading}>
        
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ya781h`}
              datas={this.getMenus ().rightMune}
              showUrlItem={false}
              style={{height: '100%'}}
            >
              <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@90eltc`} {...this.getWeaReqTopConfig ()} >
              <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@8rzt7a`}
                isNew={true}
                leftWidth={220}
                leftCom={<LeftCom ecId={`${this && this.props && this.props.ecId || ''}_LeftCom@q4xoje`} />}
                showLeft={this.state.showLeft}
                onCollapse={showLeft => this.setState ({showLeft})}
              >

                { (resData.ismonth || resData.isweek) ?  <DateSelectArea ecId={`${this && this.props && this.props.ecId || ''}_DateSelectArea@ct918q`} /> :''}
                

                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@x2r6p0`} height={_height - 130}>
                  {noDataMessage && noDataMessage.length > 0
                    ? <div style={{position: 'relative', height: 230}}>
                        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ld9q63`} {...this.state}>
                          <div style={{color: '#F00'}}>
                            {noDataMessage}
                          </div>
                        </WeaAlertPage>
                      </div>
                    : <div>

                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@0ji6qx`}>
                          <LastMonthWorkSummary ecId={`${this && this.props && this.props.ecId || ''}_LastMonthWorkSummary@lb7otg`} />
                        </Row>
                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@oh12e4`}>
                          <ThisMonthWorkPlan ecId={`${this && this.props && this.props.ecId || ''}_ThisMonthWorkPlan@sqrthv`} />
                        </Row>
                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7uavbm`}>
                          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vt546i`} md={12}>

                            {((resData.filearry &&
                              resData.filearry.length > 0) ||
                              this.store.authority.canedit) &&
                              <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@phnw6o`}
                               title={getLabel('22194','相关附件') }
                                title={
                                  <span>
                                    <i
                                      className="icon-coms-File"
                                      style={{color: 'green'}}
                                    />
                                    {' '}
                                    {getLabel('22194','相关附件') }
                                  </span>
                                }
                                color="#5DACE7"
                              >
                                <RelatedFiles ecId={`${this && this.props && this.props.ecId || ''}_RelatedFiles@gr4pda`}
                                  refFile={this.refFile}
                                  doOperation={() =>
                                    this.doOperation (this.state.operation)}
                                />
                              </SearchGroupBorderLeft>}

                            {resData.planid &&
                              resData.planid.length > 0 &&
                              <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@w844xe`}
                                title={
                                  <span>
                                    <i
                                      className="icon-coms-Need-feedback"
                                      style={{color: 'green'}}
                                    />
                                    {' '}
                                    {getLabel('33956','意见反馈') }
                                  </span>
                                }
                                color="#52BB65 "
                              >
                                <Feedback ecId={`${this && this.props && this.props.ecId || ''}_Feedback@sdtdbz`} />
                              </SearchGroupBorderLeft>}
                          </Col>
                          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vo2thf`} md={1} />
                          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vrfa62`} md={11}>   
                          { (this.store.tabSelectKey==1  || (resData.alinks.length>0 && this.store.tabSelectKey=='2') ) && <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@2g37ax`} title={getLabel('24969','相关链接')  } color="#F5A244" >
                             
                             {this.store.tabSelectKey=='1' && resData.isperformance==true && 
                               <div className='planview-alink'>
                                 <a  target='_blank' 
                                 href={`/spa/workrelate/static/index.html#/main/workrelate/performance/accessView?year=${dateSelect.year}&type1=1&type2=${dateSelect.month}&resourceid=${resData.resourceid}`}
                                 title={`${resData.resourcename}${getLabel('508616','目标绩效考核') }(${dateSelect.year}-${showMonth})`}
                                 >
                                   {`${resData.resourcename}${getLabel('508616','目标绩效考核') }(${dateSelect.year}-${showMonth})`}
                                 </a>
                               </div>
                             }

                             {(resData.alinks && resData.alinks.length>0)?<span>
                               {resData.alinks.map(v=>{
                                 return <div className='planview-alink'><a title={v.linkname} target='_blank' href={v.linkurl}>
                                 {v.linkname}
                                 </a></div>
                               })}
                             </span>:""}

                           </SearchGroupBorderLeft>
                          }                                                                  
                            
                            {resData.planid &&
                              resData.planid.length > 0 &&
                              <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@6c1aq6`}
                                title={
                                  <span>
                                    <i
                                      className="icon-coms-Batch-sharing"
                                      style={{color: 'blue'}}
                                    />
                                    {' '}
                                    {getLabel('509020','报告共享') }
                                  </span>
                                }
                                color="#4F97FF"
                              >
                                <ReportShare ecId={`${this && this.props && this.props.ecId || ''}_ReportShare@pz2dzm`} ref={this.shareRef} />
                              </SearchGroupBorderLeft>}
                            {resData.planid &&
                              resData.planid.length > 0 &&
                              <SearchGroupBorderLeft ecId={`${this && this.props && this.props.ecId || ''}_SearchGroupBorderLeft@c4mxvu`}
                                title={
                                  <span>
                                    <i
                                      className="icon-coms-Print-log"
                                      style={{color: 'green'}}
                                    />
                                    {' '}
                                    {getLabel('32061','操作日志') }
                                  </span>
                                }
                                color="#7E71F8"
                              >
                                <PlanLog ecId={`${this && this.props && this.props.ecId || ''}_PlanLog@pkqrhv`} />
                              </SearchGroupBorderLeft>}

                          </Col>

                        </Row>
                     <PlanSummaryModal ecId={`${this && this.props && this.props.ecId || ''}_PlanSummaryModal@sm49gi`} />

                      </div>}

                </WeaNewScroll>

              </WeaLeftRightLayout>
              </WeaReqTop>
            </WeaRightMenu>
         </Spin>
         
          }
      </div>
    );
  }
}
